package com.zhiyou100.action01;

import lombok.Data;
import lombok.SneakyThrows;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author yang
 * @className Demo05
 * @packageName com.zhiyou100.action01
 * @Description TODO 日期
 * @date 2020-08-21 16:46
 */
@Controller
@RequestMapping("/d5")
public class Demo05 {

    /**
     * 如果要传递日期方案一：传递字符串，在 action 中转为 日期
     *
     * @param sname 名字
     * @param sage  年龄
     * @param sdate 日期
     * @return String
     */
    @SneakyThrows
    @RequestMapping("/m1.action")
    public String method01(String sname, String sage, String sdate) {
        System.out.println(sname + " :" + sage + " : " + sdate);

        final Date parse = new SimpleDateFormat("yyyy-MM-dd").parse(sdate);
        System.out.println(sname + ": " + sage + ": " + parse.toLocaleString());
        return "test01/success";
    }


    @RequestMapping("/m2.action")
    public String method02(String sname, String sage, Date sdate) {
        System.out.println(sname + " :" + sage + " : " + sdate.toLocaleString());

        //final Date parse = new SimpleDateFormat("yyyy-MM-dd").parse(sdate);
        //System.out.println(sname + ": " + sage + ": " + parse.toLocaleString());
        return "test01/success";
    }


    /**
     * 自定义一个 日期属性编辑器
     * @param request HttpServletRequest
     * @param binder binder
     */
    @InitBinder
    public void myDateBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        binder.registerCustomEditor(Date.class, new CustomDateEditor(simpleDateFormat, true));
    }
}
